import { apiLogin, apiLogout, apiGetInfo, apiGetMenuTree } from '@/api/admin'
import { apiGetOssToken } from '@/api/upload'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
import Layout from '@/layout'

const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        roles: [],
        routes: [],
        ossToken: {},
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_ROUTES: (state, list) => {
        state.routes = constantRoutes.concat(list)
    },
    SET_OSSTOKEN: (state, data) => {
        state.ossToken = data
    },
}

const actions = {
    // 登录
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            apiLogin(userInfo).then(response => {
                const { tokenName, tokenValue } = response.data;
                commit('SET_TOKEN', tokenValue);
                setToken(JSON.stringify({ [tokenName]: tokenValue }));
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取管理员信息
    getInfo({ commit }) {
        return new Promise((resolve, reject) => {
            apiGetInfo().then(({ data }) => {
                if (!data) {
                    reject('验证失败，请重新登录。')
                }
                const { icon, nickName } = data
                commit('SET_AVATAR', icon)
                commit('SET_NAME', nickName)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取菜单树
    getMenuTree() {
        return new Promise((resolve, reject) => {
            apiGetMenuTree().then(async response => {
                resolve(response.data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 生成路由表
    generateRoutes({ commit }, menuTree) {
        return new Promise(resolve => {
            const getItem = (item) => {
                const { sort, path, redirect, component, title, hidden } = item
                const obj = {
                    sort, path, name: path,
                    component: component == 'layout' ? Layout : resolve => require([`@/views/${component}`], resolve),
                    meta: { title, icon: title }
                }
                if (redirect) obj['redirect'] = redirect
                if (hidden == 1) obj['hidden'] = true
                return obj
            }
            let accessedRoutes = [] //路由表
            const resources = new Set() //权限表
            // 将后端返回的菜单数据合成路由表
            for (let a = 0; a < menuTree.length; a++) {
                const item = getItem(menuTree[a])
                // 二级菜单
                const { children } = menuTree[a]
                if (children && children.length > 0) {
                    let arr = []
                    for (let b = 0; b < children.length; b++) {
                        const arrItem = getItem(children[b])
                        // 三级菜单
                        // const { children: children2 } = children[b]
                        // if (children2 && children2.length > 0) {
                        //     let arr2 = []
                        //     for (let c = 0; c < children2.length; c++) {
                        //         arr2.push(getItem(children2[c]))
                        //     }
                        //     arr2.sort((a, b) => a.sort - b.sort)
                        //     arrItem.children = arr2
                        // }
                        arr.push(arrItem)
                        // 功能权限
                        const resourcesList = children[b].children
                        if (resourcesList && resourcesList.length > 0) {
                            resourcesList.forEach(element => {
                                resources.add(...element.resources)
                            })
                        }
                    }
                    arr.sort((a, b) => a.sort - b.sort)
                    item.children = arr
                }
                accessedRoutes.push(item)
            }
            commit('SET_ROLES', Array.from(resources)) // 功能权限
            accessedRoutes.sort((a, b) => a.sort - b.sort) //排序
            commit('SET_ROUTES', accessedRoutes) //路由
            resolve(accessedRoutes)
        })
    },

    // 获取阿里云ossToken
    getOssToken({ commit }) {
        return new Promise((resolve, reject) => {
            apiGetOssToken().then(({ data }) => {
                data.tokenTime = new Date().getTime()
                commit('SET_OSSTOKEN', data)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 退出登录
    logout({ commit }) {
        return new Promise((resolve, reject) => {
            apiLogout().then(() => {
                removeToken() // must remove  token  first
                resetRouter()
                commit('RESET_STATE')
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    },

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
